//
//  DBTextView.swift
//  大波微博swift
//
//  Created by 大波 on 16/3/7.
//  Copyright © 2016年 zhaojin. All rights reserved.
//

import UIKit

class DBTextView: UITextView {
    
    /// 占位文本
    var placeholderString: String? {
        
        didSet{
            
            placeholderLabel.text = placeholderString
            
            placeholderLabel.sizeToFit()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        
        super.init(frame: frame, textContainer: textContainer)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self)
    }
    
    @objc private func textDidChange() {
        
//        print("text: \(text)")
//        
//        print("hasText: \(hasText())")
        
        placeholderLabel.hidden = hasText()
    }
    
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 懒加载
    
    private lazy var placeholderLabel: UILabel = {
    
        let placeholder = UILabel(textColor: UIColor.lightGrayColor(), font: 14)
        
        placeholder.translatesAutoresizingMaskIntoConstraints = false
        
        self.addSubview(placeholder)
        
        self.addConstraint(NSLayoutConstraint(item: placeholder, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        
        self.addConstraint(NSLayoutConstraint(item: placeholder, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        
        return placeholder
    }()
}
